<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class quiz extends template_plugin
{
	var $ipsclass;
	
	var $name = "Quiz";
	var $multiple = 0;
	var $cache_array = array(
								'ibm_quizzes' => array('Quiz information cache','quiz_cache'),
								'ibm_quiz_question' => array('Quiz question cache','question_cache')
							 );
	
	function quiz_cache()
	{
		$this->ipsclass->cache['ibm_quizzes'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_quizzes'));
		$this->ipsclass->DB->exec_query();
		while($quiz = $this->ipsclass->DB->fetch_row())
		{
			$quiz['q_prize_items'] = unserialize($quiz['q_prize_items']);
			$this->ipsclass->cache['ibm_quizzes'][$quiz['quiz_id']] = $quiz;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'ibm_quizzes', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function question_cache()
	{
		$this->ipsclass->cache['ibm_quiz_question'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_quiz_question'));
		$this->ipsclass->DB->exec_query();
		while($question = $this->ipsclass->DB->fetch_row())
		{
			$question['choices'] = unserialize($question['choices']);
			$question['answer'] = unserialize($question['answer']);
			$this->ipsclass->cache['ibm_quiz_question'][$question['quiz_id']][$question['question_id']] = $question;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'ibm_quiz_question', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function acp()
	{
		// Yes redirect again >_>
		$redirect = array(
								'list' => 'list_quizes',
								'add' => 'add_quiz',
								'edit' => 'edit_quiz',
								'save' => 'save_quiz',
								'delete' => 'delete_quiz',
								'player' => 'list_players',
								'question' => 'list_questions',
								'qform' => 'add_question_form',
								'qadd' => 'add_question_done',
								'qedit' => 'edit_question_form',
								'qsave' => 'edit_question_done',
								'qdelete' => 'delete_question',
							);
		if(!$redirect[$this->ipsclass->input['action']])
		{
			$this->ipsclass->input['action'] = 'list';
		}
		
		$function = 'acp_'.$redirect[$this->ipsclass->input['action']];
		$this->$function();
	}
	
	function acp_list_quizes()
	{
		$this->ipsclass->admin->page_title  = "Welcome to managing the quizzes";
		$this->ipsclass->admin->page_detail = "Welcome to managing the quizzes. Here you can add/edit/delete quizzes.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Quizzes' );
		
		$this->ipsclass->adskin->td_header[] = array( "Name/Description"       , "" );
		$this->ipsclass->adskin->td_header[] = array( "# of Questions"         , "" );
		$this->ipsclass->adskin->td_header[] = array( "Time Ending"            , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"                , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Quizzes");
		
		if(is_array($this->ipsclass->cache['ibm_quizzes']) and count($this->ipsclass->cache['ibm_quizzes']))
		{
			foreach($this->ipsclass->cache['ibm_quizzes'] as $q_id => $quiz)
			{
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																					"<b>".$quiz['q_name']."</b><br />".$quiz['q_description'],
																					$this->ipsclass->do_number_format(count($this->ipsclass->cache['ibm_quiz_question'][$q_id])),
																					$quiz['q_ending_time'] == 0 ? "Indefinite" : $this->ipsclass->get_date($quiz['q_ending_time'],'LONG'),
																					"<img id=\"menu_{$q_id}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																			)	);
				
				$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$q_id}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=edit&quiz={$q_id}'>Edit Quiz Information</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=question&quiz={$q_id}'>Add/Edit/Delete Quiz Questions</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=delete&quiz={$q_id}'>Delete Quiz</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=player&quiz={$q_id}'>View Players</a>\"
      )     );
 </script>";
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No Quizzes made yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','add'),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$date = $this->ipsclass->unixstamp_to_human(time() + 604800);
		$default = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Add a Quiz");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name</b><br />The name of the quiz.",
																			  $this->ipsclass->adskin->form_input("q_name")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Description</b>: The description for the quiz.<br />".$this->ipsclass->han_editor->show_editor( "", 'q_description' ), 'left', 'tablerow1');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Maximum number of tries on this quiz</b><br />The number of tries one person can take before passing this quiz.<br /><i>0 for unlimited tries</i>",
																			  $this->ipsclass->adskin->form_simple_input("q_tries","0")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Percent correct to pass the quiz</b><br />The percent correct in order to pass the quiz when taken.",
																			  $this->ipsclass->adskin->form_simple_input("q_percent_win",50)."%"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Quiz Ending Time</b><br />Input Format (24-hour time): MM/DD/YYYY HH:MM<br /><i>Input nothing for quiz not to end.</i>",
																			  $this->ipsclass->adskin->form_input("q_ending_time",$default)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Number of minutes for a person to attempt on the quiz</b><br />Used to prevent people looking up answers.<br /><i>Input 0 to disable or have infinite time to try the quiz.</i>",
																			  $this->ipsclass->adskin->form_simple_input("q_timeout","0")." minutes"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Prize Money</b><br />The amount of ".$this->ipsclass->vars['market_currency']." the user wins when passing the quiz.",
																			  $this->ipsclass->vars['market_prefix'].$this->ipsclass->adskin->form_simple_input("q_prize_money",0).$this->ipsclass->vars['market_suffix']
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Prize Items</b><br />The items an user gets when passing the quiz",
																			  $this->ipsclass->market_admin->compile_item_list("q_prize_items")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Add Quiz");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_add_quiz()
	{
        if($this->ipsclass->input['q_ending_time'])
        {
			list($date, $time) = explode(" ",$this->ipsclass->input['q_ending_time']);
			list($month,$day,$year) = explode("/",$date);
			list($hour,$minute) = explode(":",$time);
			if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
			{
				$this->ipsclass->input['q_ending_time'] = $this->ipsclass->convert_local_date_to_unix( array( 'month'  => intval($month),
																											  'day'    => intval($day),
																											  'year'   => intval($year),
																											  'hour'   => intval($hour),
																											  'minute' => intval($minute) ) );
			}
			else
			{
				$this->ipsclass->input['q_ending_time'] = 0;
			}
		}
		else
		{
			$this->ipsclass->input['q_ending_time'] = 0;
		}
		
		$this->ipsclass->DB->do_insert('market_quizzes',array(
																'q_name' => $this->ipsclass->input['q_name'],
																'q_description' => $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->han_editor->process_raw_post( 'q_description' ) ) ),
																'q_tries' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_tries'],'int'),
																'q_percent_win' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_percent_win'],'float'),
																'q_ending_time' => $this->ipsclass->input['q_ending_time'],
																'q_timeout' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_timeout'],'int'),
																'q_prize_money' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_prize_money'],'int'),
																'q_prize_items' => serialize($this->ipsclass->market_admin->parse_input_item_list('q_prize_items')),
										)					);
		
		$this->quiz_cache();
		
		$this->ipsclass->admin->save_log("ibMarket: Quiz Added(".$this->ipsclass->input['q_name'].")");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Quiz, ".$this->ipsclass->input['q_name'].", added...");
	}
	
	function acp_edit_quiz()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->admin->page_title  = "Welcome to editing a quiz";
		$this->ipsclass->admin->page_detail = "Welcome to editing a quiz.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Quizzes' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=edit&amp;quiz='.$this->ipsclass->input['quiz'], 'Edit Quiz Information' );
		
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'] ) );
			$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'] = $this->ipsclass->parser->convert_ipb_html_to_html( $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'] );
		}
		else
		{
			$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'] = $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'] );
		}
        
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','save'),
																	array('quiz',$this->ipsclass->input['quiz']),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$date = $this->ipsclass->unixstamp_to_human($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_ending_time']);
		$default = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Edit Quiz");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name</b><br />The name of the quiz.",
																			  $this->ipsclass->adskin->form_input("q_name", $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_name'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Description</b>: The description for the quiz. <br />".$this->ipsclass->han_editor->show_editor( $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description'], 'q_description' ), 'left', 'tablerow3');
			
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Maximum number of tries on this quiz</b><br />The number of tries one person can take before passing this quiz.<br /><i>0 for unlimited tries</i>",
																			  $this->ipsclass->adskin->form_simple_input("q_tries",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Percent correct to pass the quiz</b><br />The percent correct in order to pass the quiz when taken.",
																			  $this->ipsclass->adskin->form_simple_input("q_percent_win",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_percent_win'])."%"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Quiz Ending Time</b><br />Input Format (24-hour time): MM/DD/YYYY HH:MM<br /><i>Input nothing for quiz not to end.</i>",
																			  $this->ipsclass->adskin->form_input("q_ending_time",$default)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Number of minutes for a person to attempt on the quiz</b><br />Used to prevent people looking up answers.<br /><i>Input 0 to disable or have infinite time to try the quiz.</i>",
																			  $this->ipsclass->adskin->form_simple_input("q_timeout",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'])." minutes"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Prize Money</b><br />The amount of ".$this->ipsclass->vars['market_currency']." the user wins when passing the quiz.",
																			  $this->ipsclass->vars['market_prefix'].$this->ipsclass->adskin->form_simple_input("q_prize_money",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_money']).$this->ipsclass->vars['market_suffix']
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Prize Items</b><br />The items an user gets when passing the quiz",
																			  $this->ipsclass->market_admin->compile_item_list("q_prize_items",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_items'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Save Quiz");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_save_quiz()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
        if($this->ipsclass->input['q_ending_time'])
        {
			list($date, $time) = explode(" ",$this->ipsclass->input['q_ending_time']);
			list($month,$day,$year) = explode("/",$date);
			list($hour,$minute) = explode(":",$time);
			if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
			{
				$this->ipsclass->input['q_ending_time'] = $this->ipsclass->convert_local_date_to_unix( array( 'month'  => intval($month),
																											  'day'    => intval($day),
																											  'year'   => intval($year),
																											  'hour'   => intval($hour),
																											  'minute' => intval($minute) ) );
			}
			else
			{
				$this->ipsclass->input['q_ending_time'] = 0;
			}
		}
		else
		{
			$this->ipsclass->input['q_ending_time'] = 0;
		}
		
		$this->ipsclass->DB->do_update('market_quizzes',array(
																'q_name' => $this->ipsclass->input['q_name'],
																'q_description' => $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->han_editor->process_raw_post( 'q_description' ) ) ),
																'q_tries' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_tries'],'int'),
																'q_percent_win' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_percent_win'],'float'),
																'q_ending_time' => $this->ipsclass->input['q_ending_time'],
																'q_timeout' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_timeout'],'int'),
																'q_prize_money' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['q_prize_money'],'int'),
																'q_prize_items' => serialize($this->ipsclass->market_admin->parse_input_item_list('q_prize_items')),
					),"quiz_id=".$this->ipsclass->input['quiz']);
		
		$this->quiz_cache();
		
		$this->ipsclass->admin->save_log("ibMarket: Quiz Edited(".$this->ipsclass->input['q_name'].")");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Quiz, ".$this->ipsclass->input['q_name'].", editted...");
	}
	
	function acp_delete_quiz()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_quizzes','where'=>"quiz_id=".$this->ipsclass->input['quiz']));
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_quiz_question','where'=>"quiz_id=".$this->ipsclass->input['quiz']));
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_quiz_taken','where'=>"quiz_id=".$this->ipsclass->input['quiz']));
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_quiz_sessions','where'=>"quiz_id=".$this->ipsclass->input['quiz']));
		
		$this->ipsclass->admin->save_log("ibMarket: Quiz Deleted(".$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_name'].")");
		
		$this->quiz_cache();
		$this->question_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Quiz deleted...");
	}
	
	function acp_list_players()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->load_language('lang_market');
		
		$this->ipsclass->admin->page_title  = "Welcome to viewing the quiz players";
		$this->ipsclass->admin->page_detail = "Welcome to viewing the quiz players.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Quizzes' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=player&amp;quiz='.$this->ipsclass->input['quiz'], 'View Players' );
		
		$this->ipsclass->adskin->td_header[] = array( "Member Name"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address"      , "" );
		$this->ipsclass->adskin->td_header[] = array( "Time Started"    , "" );
		$this->ipsclass->adskin->td_header[] = array( "Time Finished"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Percent Correct" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Quiz Players");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 't.*',
												'from' => array('market_quiz_taken'=>'t'),
												'where' => "t.quiz_id=".$this->ipsclass->input['quiz'],
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name, m.mgroup',
																				'from' => array('members'=>'m'),
																				'where' => "m.id=t.member_id",
																				'type' => 'left',
																			),
																	),
												'order' => "percent_correct DESC, time_start ASC",
										)	);
		$this->ipsclass->DB->exec_query();
		while($member = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$this->ipsclass->market_admin->format_name($member['member_id'], $member['members_display_name'],$member['mgroup']),
																				$member['ip_address'],
																				$this->ipsclass->get_date($member['time_start'],'LONG'),
																				$this->ipsclass->numbers->time_unit($member['time_taken']-$member['time_start'],'LONG'),
																				$this->ipsclass->do_number_format($member['percent_correct'])."%",
																		)	);
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_list_questions()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->admin->page_title  = "Welcome to managing questions for a quiz";
		$this->ipsclass->admin->page_detail = "Welcome to managing questions for a quiz.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Quizzes' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=question&amp;quiz='.$this->ipsclass->input['quiz'], 'Manage Questions' );
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Quiz Information");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name</b>",
																			  $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_name']
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Description</b><br />The description for the quiz.",
																			  $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_description']
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Maximum number of tries on this quiz</b>",
																			  $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'] ? $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'] : "Unlimited"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Percent correct to pass the quiz</b>",
																			  $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_percent_win']."%"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Quiz Ending Time</b>",
																			  $this->ipsclass->get_date($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_ending_time'],'LONG')
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Number of minutes for a person to attempt on the quiz</b>",
																			  $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout']." minutes"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Prize Money</b>",
																			  $this->ipsclass->vars['market_prefix'].$this->ipsclass->do_number_format($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_money']).$this->ipsclass->vars['market_suffix']
																	 )      );
		
		$items = "";
		foreach($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_items'] as $item_id => $quanity)
		{
			$items .= "<b>".$this->ipsclass->cache['market_items'][$item_id]['item_name']."</b> x ".$quanity."<br />\n";
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Prize Items</b><br />The items an user gets when passing the quiz",
																			  $items
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->adskin->td_header[] = array( "Question"       , "" );
		$this->ipsclass->adskin->td_header[] = array( "Answer"         , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"        , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Questions");
		
		if(is_array($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']]) and count($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']]))
		{
			foreach($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']] as $q_id => $question)
			{
				$answer = array();
				if($question['q_type'] == 'single')
				{
					$answer = $question['answer'];
				}
				else
				{
					foreach($question['answer'] as $index)
					{
						$answer[] = $question['choices'][$index];
					}
				}
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																					$question['question'],
																					implode(", ", $answer),
																					"<img id=\"menu_{$q_id}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																			)	);
				
				$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$q_id}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=qedit&quiz={$this->ipsclass->input['quiz']}&question={$q_id}'>Edit Question</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=qdelete&quiz={$this->ipsclass->input['quiz']}&question={$q_id}'>Delete Question</a>\"
      )     );
 </script>";
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No questions made yet",'center');
		}
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic($this->ipsclass->adskin->js_make_button("Add a question","{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=qform&quiz={$this->ipsclass->input['quiz']}"),'center','tablerow3');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_add_question_form()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->admin->page_title  = "Welcome to adding a question for a quiz";
		$this->ipsclass->admin->page_detail = "Welcome to adding a question for a quiz.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Quizzes' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=question&amp;quiz='.$this->ipsclass->input['quiz'], 'Manage Questions' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=qform&amp;quiz='.$this->ipsclass->input['quiz'], 'Add Question' );
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','qadd'),
																	array('quiz',$this->ipsclass->input['quiz']),
														)	);
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Add a Question");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Type of Question</b>",
																			  $this->ipsclass->adskin->form_dropdown("q_type",array(array('single',"Input Answer"),array('smultiple',"Multiple Choice, Single Answer"),array('mmultiple',"Multiple Choice, Multiple Answer")),'',"onchange='parse_question()'")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Question</b><br />BBcode allowed",
																			  $this->ipsclass->adskin->form_simple_input("question","",45)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Is the answer case sensitive?</b><br />By enabling this, answers like 'WoRd' and 'word' and 'wOrD' are considered the same. Option only avalible on 'Input Answer'.",
																			  $this->ipsclass->adskin->form_checkbox("case_sensitive",1,1,array("onclick='load_question()'"))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Is the answer space sensitive?</b><br />By enabling this, answers like 'W o r d' and 'Word' are considered the same. Option only avalible on 'Input Answer'.",
																			  $this->ipsclass->adskin->form_checkbox("space_sensitive",1,1,array("onclick='load_question()'"))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Match how many choices before being correct?</b><br />If this is 3 and there are 5 possible correct answers, the user has to get 3 of the answers before this question is considered correct. Option only avalible on 'Input Answer' or 'Multiple Choice, Multiple Answer'. Input 0 to match all answers.",
																			  $this->ipsclass->adskin->form_input("match_choice",1,'text',"onkeyup='load_question();this.focus();'")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>What is the weight of this question?</b><br />If you input 2, this question has twice the value than any other question with the weight of 1.",
																			  $this->ipsclass->adskin->form_simple_input("weight",1)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>What is the penalty for getting this question wrong?</b><br />If you input .5, it will deduct .5 from the questions correct.",
																			  $this->ipsclass->adskin->form_simple_input("penalty",0)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Does an unanswered question count as an penalty?</b>",
																			  $this->ipsclass->adskin->form_yes_no("blank_penalty",0)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= <<<EOF
<div class='tableborder'>
	<div class='tableheaderalt'>Choices/Answers</div>
	<table width='100%' cellspacing='0' cellpadding='5' align='center' border='0' id='choices'>
		<tr>
			<td class='tablesubheader' align='center'>Choice</td>
			<td class='tablesubheader' align='center' width='5%'>Answer</td>
			<td class='tablesubheader' align='center' width='5%'>Delete</td>
		</tr>
		<tr>
			<td class='tablerow3' align='center' colspan='3'><input type='button' value="Add Choice/Answer" class='textinput' onclick="add_choice()"></td>
		</tr>
	</table>
</div>
<br />
EOF;
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Add Question");
		
		$this->ipsclass->html .= <<<EOF
<script type="text/javascript">
var case_checked;
var space_checked;
var match_choice;
var single_answer = -1;
var choices = 
{
}
var was_type = document.theAdminForm.q_type.value;
function load_question()
{
	if(was_type != 'smultiple')
	{
		match_choice = document.theAdminForm.match_choice.value;
	}
	if(was_type == 'single')
	{
		case_checked = document.theAdminForm.case_sensitive.checked;
		space_checked = document.theAdminForm.space_sensitive.checked;
	}
	parse_question();
}
function convert_input()
{
	var form = document.theAdminForm;
	for(var i in choices)
	{
		try
		{
			choices[i][0] = document.getElementById('choice_'+i).value;
			if(was_type == 'mmultiple')
			{
				choices[i][1] = document.getElementById('answer_'+i).checked;
			}
			if(was_type == 'smultiple' && document.getElementById('answer_'+i).checked)
			{
				single_answer = i;
			}
		}
		catch(e) { }
	}
}
function parse_question()
{
	convert_input();
	var form = document.theAdminForm;
	was_type = form.q_type.value;
	if(form.q_type.value == 'single')
	{
		form.case_sensitive.checked = case_checked;
		form.space_sensitive.checked = space_checked;
		form.case_sensitive.disabled = false;
		form.space_sensitive.disabled = false;
	}
	else
	{
		form.case_sensitive.checked = false;
		form.space_sensitive.checked = false;
		form.case_sensitive.disabled = true;
		form.space_sensitive.disabled = true;
	}
	if(form.q_type.value == 'smultiple')
	{
		document.theAdminForm.match_choice.value = 1;
		document.theAdminForm.match_choice.disabled = true;
	}
	else
	{
		document.theAdminForm.match_choice.value = match_choice;
		document.theAdminForm.match_choice.disabled = false;
	}
	
	var tableobj = document.getElementById('choices');
	while(tableobj.rows.length > 2)
	{
		tableobj.deleteRow(tableobj.rows.length - 2);
	}
	for(var i in choices)
	{
		newRow = tableobj.insertRow(tableobj.rows.length-1);
		newCell = newRow.insertCell(0);
		newCell.innerHTML = "<input type='text' name='choice["+i+"]' id='choice_"+i+"' value='"+choices[i][0]+"' size='30' class='textinput'>";
		newCell.className = 'tablerow1';
		newCell = newRow.insertCell(1);
		if(form.q_type.value == 'single')
		{
			newCell.innerHTML = "<input type='checkbox' value='1' checked='checked' disabled='disabled'>";
		}
		else if(form.q_type.value == 'smultiple')
		{
			if(single_answer == i)
			{
				newCell.innerHTML = "<input type='radio' name='answer' id='answer_"+i+"' value='"+i+"' checked='checked'>";
			}
			else
			{
				newCell.innerHTML = "<input type='radio' name='answer' id='answer_"+i+"' value='"+i+"'>";
			}
		}
		else if(form.q_type.value == 'mmultiple')
		{
			if(choices[i][1])
			{
				newCell.innerHTML = "<input type='checkbox' name='answer["+i+"]' id='answer_"+i+"' value='1' checked='checked'>";
			}
			else
			{
				newCell.innerHTML = "<input type='checkbox' name='answer["+i+"]' id='answer_"+i+"' value='1'>";
			}
		}
		newCell.className = 'tablerow2';
		newCell = newRow.insertCell(2);
		newCell.innerHTML = "<a href='#' title='Remove Choice/Answer' style='color:red;font-weight:bold' onclick=\"return remove_choice("+i+")\">[X]</a>";
		newCell.className = 'tablerow3';
	}
}
function add_choice()
{
	var maxid = 0;
	for(var i in choices)
	{
		i = parseInt(i);
		if(i > maxid)
		{
			maxid = i;
		}
	}
	maxid++;
	choices[maxid] = ["",false];
	parse_question();
}
function remove_choice(id)
{
	delete(choices[id]);
	parse_question();
	return false;
}

load_question();
</script>
EOF;
		
		$this->ipsclass->admin->output();
	}
	
	function acp_add_question_done()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		if($this->ipsclass->input['q_type'] != 'single')
		{
			$this->ipsclass->input['case_sensitive'] = 0;
			$this->ipsclass->input['space_sensitive'] = 0;
		}
		
		$parser = new parse_bbcode();
		$parser->ipsclass =& $this->ipsclass;
		$parser->allow_update_caches = 0;
		$parser->bypass_badwords = intval($this->ipsclass->member['g_bypass_badwords']);
		$parser->parse_smilies = 1;
		$parser->parse_html = 0;
		$parser->parse_bbcode = 1;
		$parser->parse_n12br = 0;
		
		$answer = array();
		$choice = array();
		$cleaned = array();
		if(is_array($this->ipsclass->input['choice']) && count($this->ipsclass->input['choice']) != 0)
		{
			foreach($this->ipsclass->input['choice'] as $index => $text)
			{
				$index = intval($index);
				$text = trim($this->ipsclass->parser->strip_all_tags($text));
				if($text == "")
				{
					continue;
				}
				if($this->ipsclass->input['q_type'] == 'single')
				{
					$ctext = $text;
					if($this->ipsclass->input['case_sensitive'])
					{
						$ctext = strtolower($ctext);
					}
					if($this->ipsclass->input['space_sensitive'])
					{
						$ctext = $this->remove_white_space($ctext);
					}
					if(in_array($ctext,$cleaned))
					{
						continue;
					}
					$cleaned[] = $ctext;
					$answer[] = $text;
				}
				elseif($this->ipsclass->input['q_type'] == 'smultiple')
				{
					if(in_array($text,$choice))
					{
						if($index == $this->ipsclass->input['answer'])
						{
							$answer[] = array_search($text,$choice);
						}
						continue;
					}
					$choice[] = $text;
				
					if($index == $this->ipsclass->input['answer'])
					{
						$answer[] = count($choice)-1;
					}
				}
				elseif($this->ipsclass->input['q_type'] == 'mmultiple')
				{
					if(in_array($text,$choice))
					{
						if($this->ipsclass->input['answer'][$index])
						{
							$key = array_search($text,$choice);
							if(!in_array($key,$answer))
							{
								$answer[] = $key;
							}
						}
						continue;
					}
					$choice[] = $text;
				
					if($this->ipsclass->input['answer'][$index])
					{
						$answer[] = count($choice)-1;
					}
				}
			}
		}
		
		if(count($answer) == 0 || ($this->ipsclass->input['q_type'] != 'single' && count($choice) == 0))
		{
			$this->ipsclass->admin->error("You must have some answers and/or choices inputted");
		}
		if($this->ipsclass->input['q_type'] != 'single' && count($choice) == 1)
		{
			$this->ipsclass->admin->error("For Multiple Choice, you have have at least TWO choices and ONE answer");
		}
		
		$this->ipsclass->input['match_choice'] = intval($this->ipsclass->input['match_choice']);
		if($this->ipsclass->input['s_multiple'] == 'smultiple')
		{
			$this->ipsclass->input['match_choice'] = 1;
		}
		else
		{
			if($this->ipsclass->input['match_choice'] > count($answer))
			{
				$this->ipsclass->input['match_choice'] = count($answer);
			}
		}
		
		$this->ipsclass->DB->do_insert('market_quiz_question',array(
																		'quiz_id' => $this->ipsclass->input['quiz'],
																		'q_type' => $this->ipsclass->input['q_type'],
																		'question' => $parser->pre_display_parse($parser->pre_db_parse($this->ipsclass->input['question'])),
																		'choices' => serialize($choice),
																		'answer' => serialize($answer),
																		'case_sensitive' => intval($this->ipsclass->input['case_sensitive']) & 1,
																		'space_sensitive' => intval($this->ipsclass->input['space_sensitive']) & 1,
																		'weight' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['weight']),
																		'penalty' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['penalty']),
																		'blank_penalty' => intval($this->ipsclass->input['blank_penalty']) & 1,
																		'match_choice' => $this->ipsclass->input['match_choice'],
										)							);
		
		$this->question_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&action=question&quiz=".$this->ipsclass->input['quiz'],"Quiz question added...");
	}
	
	function acp_edit_question_form()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		$this->ipsclass->input['question'] = intval($this->ipsclass->input['question']);
		if(!is_array($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz question");
		}
		
		$this->ipsclass->admin->page_title  = "Welcome to adding a question for a quiz";
		$this->ipsclass->admin->page_detail = "Welcome to adding a question for a quiz.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Quizzes' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=question&amp;quiz='.$this->ipsclass->input['quiz'], 'Manage Questions' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=qedit&amp;quiz='.$this->ipsclass->input['quiz'].'&amp;question='.$this->ipsclass->input['question'], 'Edit Question' );
		
		$parser = new parse_bbcode();
		$parser->ipsclass =& $this->ipsclass;
		$parser->allow_update_caches = 0;
		$parser->bypass_badwords = intval($this->ipsclass->member['g_bypass_badwords']);
		$parser->parse_smilies = 1;
		$parser->parse_html = 0;
		$parser->parse_bbcode = 1;
		$parser->parse_n12br = 0;
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','qsave'),
																	array('quiz',$this->ipsclass->input['quiz']),
																	array('question_id',$this->ipsclass->input['question']),
														)	);
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Edit Question");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Type of Question</b>",
																			  $this->ipsclass->adskin->form_dropdown("q_type",array(array('single',"Input Answer"),array('smultiple',"Multiple Choice, Single Answer"),array('mmultiple',"Multiple Choice, Multiple Answer")),$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['q_type'],"onchange='parse_question()'")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Question</b><br />BBcode allowed",
																			  $this->ipsclass->adskin->form_simple_input("question",$parser->pre_edit_parse($parser->pre_db_parse($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['question'])),45)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Is the answer case sensitive?</b><br />By enabling this, answers like 'WoRd' and 'word' and 'wOrD' are considered the same. Option only avalible on 'Input Answer'.",
																			  $this->ipsclass->adskin->form_checkbox("case_sensitive",$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['case_sensitive'],1,array("onclick='load_question()'"))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Is the answer space sensitive?</b><br />By enabling this, answers like 'W o r d' and 'Word' are considered the same. Option only avalible on 'Input Answer'.",
																			  $this->ipsclass->adskin->form_checkbox("space_sensitive",$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['space_sensitive'],1,array("onclick='load_question()'"))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Match how many choices before being correct?</b><br />If this is 3 and there are 5 possible correct answers, the user has to get 3 of the answers before this question is considered correct. Option only avalible on 'Input Answer' or 'Multiple Choice, Multiple Answer'. Input 0 to match all answers.",
																			  $this->ipsclass->adskin->form_input("match_choice",$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['match_choice'],'text',"onkeyup='load_question();this.focus();'")
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>What is the weight of this question?</b><br />If you input 2, this question has twice the value than any other question with the weight of 1.",
																			  $this->ipsclass->adskin->form_simple_input("weight",$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['weight'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>What is the penalty for getting this question wrong?</b><br />If you input .5, it will deduct .5 from the questions correct.",
																			  $this->ipsclass->adskin->form_simple_input("penalty",$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['penalty'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Does an unanswered question count as an penalty?</b>",
																			  $this->ipsclass->adskin->form_yes_no("blank_penalty",$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['blank_penalty'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= <<<EOF
<div class='tableborder'>
	<div class='tableheaderalt'>Choices/Answers</div>
	<table width='100%' cellspacing='0' cellpadding='5' align='center' border='0' id='choices'>
		<tr>
			<td class='tablesubheader' align='center'>Choice</td>
			<td class='tablesubheader' align='center' width='5%'>Answer</td>
			<td class='tablesubheader' align='center' width='5%'>Delete</td>
		</tr>
		<tr>
			<td class='tablerow3' align='center' colspan='3'><input type='button' value="Add Choice/Answer" class='textinput' onclick="add_choice()"></td>
		</tr>
	</table>
</div>
<br />
EOF;
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Edit Question");
		
		$single_answer = -1;
		if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['q_type'] == 'smultiple')
		{
			$single_answer = $this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['answer'][0];
		}
		$choices = array();
		if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['q_type'] == 'single')
		{
			foreach($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['answer'] as $index => $text)
			{
				$choices[] = $index." : ['".str_replace("'","\\'",$text)."',false]";
			}
		}
		elseif($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['q_type'] == 'smultiple')
		{
			foreach($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['choices'] as $index => $text)
			{
				$choices[] = $index." : ['".str_replace("'","\\'",$text)."',false]";
			}
		}
		elseif($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['q_type'] == 'mmultiple')
		{
			foreach($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['choices'] as $index => $text)
			{
				if(in_array($index,$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]['answer']))
				{
					$choices[] = $index." : ['".str_replace("'","\\'",$text)."',true]";
				}
				else
				{
					$choices[] = $index." : ['".str_replace("'","\\'",$text)."',false]";
				}
			}
		}
		$choices = implode(",\n",$choices);
		
		$this->ipsclass->html .= <<<EOF
<script type="text/javascript">
var case_checked;
var space_checked;
var match_choice;
var single_answer = {$single_answer};
var choices = 
{
{$choices}
}
var was_type = document.theAdminForm.q_type.value;
function load_question()
{
	if(was_type != 'smultiple')
	{
		match_choice = document.theAdminForm.match_choice.value;
	}
	if(was_type == 'single')
	{
		case_checked = document.theAdminForm.case_sensitive.checked;
		space_checked = document.theAdminForm.space_sensitive.checked;
	}
	parse_question();
}
function convert_input()
{
	var form = document.theAdminForm;
	for(var i in choices)
	{
		try
		{
			choices[i][0] = document.getElementById('choice_'+i).value;
			if(was_type == 'mmultiple')
			{
				choices[i][1] = document.getElementById('answer_'+i).checked;
			}
			if(was_type == 'smultiple' && document.getElementById('answer_'+i).checked)
			{
				single_answer = i;
			}
		}
		catch(e) { }
	}
}
function parse_question()
{
	convert_input();
	var form = document.theAdminForm;
	was_type = form.q_type.value;
	if(form.q_type.value == 'single')
	{
		form.case_sensitive.checked = case_checked;
		form.space_sensitive.checked = space_checked;
		form.case_sensitive.disabled = false;
		form.space_sensitive.disabled = false;
	}
	else
	{
		form.case_sensitive.checked = false;
		form.space_sensitive.checked = false;
		form.case_sensitive.disabled = true;
		form.space_sensitive.disabled = true;
	}
	if(form.q_type.value == 'smultiple')
	{
		document.theAdminForm.match_choice.value = 1;
		document.theAdminForm.match_choice.disabled = true;
	}
	else
	{
		document.theAdminForm.match_choice.value = match_choice;
		document.theAdminForm.match_choice.disabled = false;
	}
	
	var tableobj = document.getElementById('choices');
	while(tableobj.rows.length > 2)
	{
		tableobj.deleteRow(tableobj.rows.length - 2);
	}
	for(var i in choices)
	{
		newRow = tableobj.insertRow(tableobj.rows.length-1);
		newCell = newRow.insertCell(0);
		newCell.innerHTML = "<input type='text' name='choice["+i+"]' id='choice_"+i+"' value='"+choices[i][0]+"' size='30' class='textinput'>";
		newCell.className = 'tablerow1';
		newCell = newRow.insertCell(1);
		if(form.q_type.value == 'single')
		{
			newCell.innerHTML = "<input type='checkbox' value='1' checked='checked' disabled='disabled'>";
		}
		else if(form.q_type.value == 'smultiple')
		{
			if(single_answer == i)
			{
				newCell.innerHTML = "<input type='radio' name='answer' id='answer_"+i+"' value='"+i+"' checked='checked'>";
			}
			else
			{
				newCell.innerHTML = "<input type='radio' name='answer' id='answer_"+i+"' value='"+i+"'>";
			}
		}
		else if(form.q_type.value == 'mmultiple')
		{
			if(choices[i][1])
			{
				newCell.innerHTML = "<input type='checkbox' name='answer["+i+"]' id='answer_"+i+"' value='1' checked='checked'>";
			}
			else
			{
				newCell.innerHTML = "<input type='checkbox' name='answer["+i+"]' id='answer_"+i+"' value='1'>";
			}
		}
		newCell.className = 'tablerow2';
		newCell = newRow.insertCell(2);
		newCell.innerHTML = "<a href='#' title='Remove Choice/Answer' style='color:red;font-weight:bold' onclick=\"return remove_choice("+i+")\">[X]</a>";
		newCell.className = 'tablerow3';
	}
}
function add_choice()
{
	var maxid = 0;
	for(var i in choices)
	{
		i = parseInt(i);
		if(i > maxid)
		{
			maxid = i;
		}
	}
	maxid++;
	choices[maxid] = ["",false];
	parse_question();
}
function remove_choice(id)
{
	delete(choices[id]);
	parse_question();
	return false;
}

load_question();
</script>
EOF;
		
		$this->ipsclass->admin->output();
	}
	
	function acp_edit_question_done()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->input['question_id'] = intval($this->ipsclass->input['question_id']);
		if(!is_array($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question_id']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz question");
		}
		
		if($this->ipsclass->input['q_type'] != 'single')
		{
			$this->ipsclass->input['case_sensitive'] = 0;
			$this->ipsclass->input['space_sensitive'] = 0;
		}
		
		$parser = new parse_bbcode();
		$parser->ipsclass =& $this->ipsclass;
		$parser->allow_update_caches = 0;
		$parser->bypass_badwords = intval($this->ipsclass->member['g_bypass_badwords']);
		$parser->parse_smilies = 1;
		$parser->parse_html = 0;
		$parser->parse_bbcode = 1;
		$parser->parse_n12br = 0;
		
		$answer = array();
		$choice = array();
		$cleaned = array();
		if(is_array($this->ipsclass->input['choice']) && count($this->ipsclass->input['choice']) != 0)
		{
			foreach($this->ipsclass->input['choice'] as $index => $text)
			{
				$index = intval($index);
				$text = trim($this->ipsclass->parser->strip_all_tags($text));
				if($text == "")
				{
					continue;
				}
				if($this->ipsclass->input['q_type'] == 'single')
				{
					$ctext = $text;
					if($this->ipsclass->input['case_sensitive'])
					{
						$ctext = strtolower($ctext);
					}
					if($this->ipsclass->input['space_sensitive'])
					{
						$ctext = $this->remove_white_space($ctext);
					}
					if(in_array($ctext,$cleaned))
					{
						continue;
					}
					$cleaned[] = $ctext;
					$answer[] = $text;
				}
				elseif($this->ipsclass->input['q_type'] == 'smultiple')
				{
					if(in_array($text,$choice))
					{
						if($index == $this->ipsclass->input['answer'])
						{
							$answer[] = array_search($text,$choice);
						}
						continue;
					}
					$choice[] = $text;
				
					if($index == $this->ipsclass->input['answer'])
					{
						$answer[] = count($choice)-1;
					}
				}
				elseif($this->ipsclass->input['q_type'] == 'mmultiple')
				{
					if(in_array($text,$choice))
					{
						if($this->ipsclass->input['answer'][$index])
						{
							$key = array_search($text,$choice);
							if(!in_array($key,$answer))
							{
								$answer[] = $key;
							}
						}
						continue;
					}
					$choice[] = $text;
				
					if($this->ipsclass->input['answer'][$index])
					{
						$answer[] = count($choice)-1;
					}
				}
			}
		}
		
		if(count($answer) == 0 || ($this->ipsclass->input['q_type'] != 'single' && count($choice) == 0))
		{
			$this->ipsclass->admin->error("You must have some answers and/or choices inputted");
		}
		if($this->ipsclass->input['q_type'] != 'single' && count($choice) == 1)
		{
			$this->ipsclass->admin->error("For Multiple Choice, you have have at least TWO choices and ONE answer");
		}
		
		$this->ipsclass->input['match_choice'] = intval($this->ipsclass->input['match_choice']);
		if($this->ipsclass->input['s_multiple'] == 'smultiple')
		{
			$this->ipsclass->input['match_choice'] = 1;
		}
		else
		{
			if($this->ipsclass->input['match_choice'] > count($answer))
			{
				$this->ipsclass->input['match_choice'] = count($answer);
			}
		}
		
		$this->ipsclass->DB->do_update('market_quiz_question',array(
																		'q_type' => $this->ipsclass->input['q_type'],
																		'question' => $parser->pre_display_parse($parser->pre_db_parse($this->ipsclass->input['question'])),
																		'choices' => serialize($choice),
																		'answer' => serialize($answer),
																		'case_sensitive' => intval($this->ipsclass->input['case_sensitive']) & 1,
																		'space_sensitive' => intval($this->ipsclass->input['space_sensitive']) & 1,
																		'weight' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['weight']),
																		'penalty' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['penalty']),
																		'blank_penalty' => intval($this->ipsclass->input['blank_penalty']) & 1,
																		'match_choice' => $this->ipsclass->input['match_choice'],
				),"question_id=".$this->ipsclass->input['question_id']);
		
		$this->question_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&action=question&quiz=".$this->ipsclass->input['quiz'],"Quiz question saved...");
	}
	
	function acp_delete_question()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz");
		}
		
		$this->ipsclass->input['question'] = intval($this->ipsclass->input['question']);
		if(!is_array($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$this->ipsclass->input['question']]))
		{
			$this->ipsclass->admin->error("Cannot find quiz question");
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_quiz_question','where'=>"question_id=".$this->ipsclass->input['question']));
		
		$this->question_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&action=question&quiz=".$this->ipsclass->input['quiz'],"Quiz question deleted...");
	}
	
	function acp_install()
	{
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
		
		$this->ipsclass->DB->build_query_from_cache('table_quizzes',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_quiz_question',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_quiz_taken',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_quiz_sessions',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		
		$this->quiz_cache();
		$this->question_cache();
	}
	
	function acp_uninstall()
	{
		$this->ipsclass->DB->sql_drop_table( 'market_quizzes'       );
		$this->ipsclass->DB->sql_drop_table( 'market_quiz_question' );
		$this->ipsclass->DB->sql_drop_table( 'market_quiz_taken'    );
		$this->ipsclass->DB->sql_drop_table( 'market_quiz_sessions' );
	}
	
	function run()
	{
		$this->ipsclass->load_template('skin_market_plugin');
		$this->ipsclass->load_language('lang_market_plugin');
		
		if(in_array($this->ipsclass->member['mgroup'],$this->plugin['use_permission']))
		{
			$do_redirect = array(
									'list' => 'list_quizzes',
									'quiz' => 'take_quiz',
									'submit' => 'process_answers',
									'players' => 'view_players',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		else
		{
			$do_redirect = array(
									'list' => 'list_quizzes',
									'players' => 'view_players',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		
		$func = 'run_'.$do_redirect[$this->ipsclass->input['do']];
		$this->$func();
	}
	
	function run_list_quizzes()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['quiz_list_quizzes'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}'>".$this->plugin['name']."</a>");
		
		$quizzed = array();
		$this->ipsclass->DB->build_query(array('select'=>'quiz_id,COUNT(*) as played,MAX(passed_quiz) as passed','from'=>'market_quiz_taken','where'=>"member_id=".$this->ipsclass->member['id'],'group'=>'quiz_id'));
		$this->ipsclass->DB->exec_query();
		while($taken = $this->ipsclass->DB->fetch_row())
		{
			$quizzed[$taken['quiz_id']] = $taken;
		}
		
		uasort($this->ipsclass->cache['ibm_quizzes'],array(&$this,'order'));
		foreach($this->ipsclass->cache['ibm_quizzes'] as $q_id => $quiz)
		{
			$this->ipsclass->cache['ibm_quizzes'][$q_id]['num_questions'] = $this->ipsclass->do_number_format(count($this->ipsclass->cache['ibm_quiz_question'][$q_id]));
			$this->ipsclass->cache['ibm_quizzes'][$q_id]['status'] = (($quiz['q_ending_time'] && $quiz['q_ending_time'] < time()) || count($this->ipsclass->cache['ibm_quiz_question'][$q_id]) == 0) ? $this->ipsclass->lang['quiz_closed'] : $this->ipsclass->lang['quiz_open'];
			$this->ipsclass->cache['ibm_quizzes'][$q_id]['ending_time'] = $quiz['q_ending_time'] ? $this->ipsclass->get_date($quiz['q_ending_time'],'LONG') : $this->ipsclass->lang['quiz_never'];
			$this->ipsclass->cache['ibm_quizzes'][$q_id]['played'] = $quizzed[$q_id]['played'] ? $quizzed[$q_id]['played'] : 0;
			$this->ipsclass->cache['ibm_quizzes'][$q_id]['passed'] = $quizzed[$q_id]['passed'] ? 1 : 0;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->quiz_list_quizzes();
	}
	
	function run_take_quiz()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_no_quiz'));
		}
		
		if(($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_ending_time'] && $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_ending_time'] < time()) || count($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']]) == 0)
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_no_quiz'));
		}
		
		$time_left = $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'] * 60;
		$time = time();
		if($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'])
		{
			$last = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_quiz_sessions','where'=>"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']));
			if($last)
			{
				if($time - $last['time_started'] < $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'] * 60)
				{
					$time_left = $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'] * 60 - $time + $last['time_started'];
				}
				else
				{
					$this->ipsclass->DB->do_delete('market_quiz_sessions',"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']);
					
					$this->ipsclass->DB->do_insert('market_quiz_taken',array(
																				'quiz_id' => $this->ipsclass->input['quiz'],
																				'member_id' => $this->ipsclass->member['id'],
																				'ip_address' => $this->ipsclass->ip_address,
																				'time_start' => $last['time_started'],
																				'time_taken' => $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'] * 60,
																				'percent_correct' => 0,
																				'passed_quiz' => 0,
													)						);
					
					$this->ipsclass->DB->do_insert('market_quiz_sessions',array(
																				'session_id' => $this->ipsclass->input['quiz'],
																				'quiz_id' => $this->ipsclass->input['quiz'],
																				'member_id' => $this->ipsclass->member['id'],
																				'time_started' => $time,
													)						);
				}
			}
			else
			{
				$this->ipsclass->DB->do_insert('market_quiz_sessions',array(
																			'session_id' => $this->ipsclass->input['quiz'],
																			'quiz_id' => $this->ipsclass->input['quiz'],
																			'member_id' => $this->ipsclass->member['id'],
																			'time_started' => $time,
												)						);
			}
		}
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>"COUNT(*) as played, MAX(passed_quiz) as passed",'from'=>'market_quiz_taken','where'=>"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']));
		if($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'] && $count['played'] >= $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'])
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_played_too_many'));
		}
		if($count['passed'])
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_has_passed'));
		}
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['quiz_taking_a_quiz'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}'>".$this->plugin['name']."</a>",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_name'],"<a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}&amp;do=quiz&amp;quiz=".$this->ipsclass->input['quiz']."'>".$this->ipsclass->lang['quiz_taking_a_quiz']."</a>");
		
		$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['start_time'] = time();
		
		$i = 0;
		foreach(array_keys($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']]) as $q_id)
		{
			$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$q_id]['number'] = ++$i;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->quiz_take_quiz($time_left);
	}
	
	function run_process_answers()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_no_quiz'));
		}
		
		if(($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_ending_time'] && $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_ending_time'] < time()) || count($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']]) == 0)
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_no_quiz'));
		}
		
		if($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'])
		{
			$session = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_quiz_sessions','where'=>"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']));
			if(!$session)
			{
				$this->ipsclass->Error(array('MSG'=>'incorrect_use'));
			}
			
			if($session['time_started'] + $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'] * 60 + 30 < time())
			{
				$this->ipsclass->DB->do_delete('market_quiz_sessions',"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']);
				
				$this->ipsclass->DB->do_insert('market_quiz_taken',array(
																			'quiz_id' => $this->ipsclass->input['quiz'],
																			'member_id' => $this->ipsclass->member['id'],
																			'ip_address' => $this->ipsclass->ip_address,
																			'time_start' => $session['time_started'],
																			'time_taken' => $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_timeout'] * 60,
																			'percent_correct' => 0,
																			'passed_quiz' => 0,
												)						);
				
				$this->ipsclass->Error(array('MSG'=>'quiz_too_much_time'));
			}
		}
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>"COUNT(*) as played, MAX(passed_quiz) as passed",'from'=>'market_quiz_taken','where'=>"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']));
		if($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'] && $count['played'] >= $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_tries'])
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_played_too_many'));
		}
		if($count['passed'])
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_has_passed'));
		}
		
		$func_map = array(
							'single' => 'process_input_answer',
							'smultiple' => 'process_single_multiple_choice',
							'mmultiple' => 'process_multiple_multiple_choice',
						);
		
		$total = 0;
		$correct = 0;
		foreach($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']] as $q_id => $question)
		{
			$func = $func_map[$question['q_type']];
			$result = $this->$func($q_id);
			$total += $question['weight'];
			if($result == -1)
			{
				$correct -= $question['penalty'];
			}
			elseif($result == 0 && $question['blank_penalty'])
			{
				$correct -= $question['penalty'];
			}
			elseif($result == 1)
			{
				$correct += $question['weight'];
			}
		}
		
		$time = time();
		$win = 0;
		if($correct/$total >= $this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_percent_win']/100)
		{
			$this->ipsclass->DB->do_update('members',array(
																$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->add($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_money'])
						),"id=".$this->ipsclass->member['id']);
			
			$this->ipsclass->market_class->record_reward($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_money']);
			
			foreach($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_prize_items'] as $item_id => $quanity)
			{
				$expired = $this->ipsclass->cache['market_items'][$item_id]['expire_time'] > 0 ? $time + $this->ipsclass->cache['market_items'][$item_id]['expire_time'] * $this->ipsclass->cache['market_items'][$item_id]['expire_unit'] : 0;
				for($i = 0; $i < $quanity; $i++)
				{
					$inv_item = array(
										'member_id' => $this->ipsclass->member['id'],
										'item' => $item_id,
										'price_bought' => $this->ipsclass->cache['market_items'][$item_id]['price'],
										'resell_price' => $this->ipsclass->cache['market_items'][$item_id]['resell'],
										'time_bought' => $time,
										'settings' => '',
										'expired' => $expired,
									);
					if($this->ipsclass->market_class->items_loaded[$item_id]->public_on_create_item($inv_item))
					{
						$this->ipsclass->DB->do_insert('market_inventory',$inv_item);
					}
				}
			}
			
			$win = 1;
		}
		
		$this->ipsclass->DB->do_delete('market_quiz_sessions',"quiz_id=".$this->ipsclass->input['quiz']." AND member_id=".$this->ipsclass->member['id']);
				
		$this->ipsclass->DB->do_insert('market_quiz_taken',array(
																	'quiz_id' => $this->ipsclass->input['quiz'],
																	'member_id' => $this->ipsclass->member['id'],
																	'ip_address' => $this->ipsclass->ip_address,
																	'time_start' => $session['time_started'],
																	'time_taken' => $time,
																	'percent_correct' => $correct/$total*100,
																	'passed_quiz' => $win,
										)						);
		
		$this->ipsclass->market_class->redirect($win ? 'quiz_passed' : 'quiz_no_pass',"plugin=".$this->ipsclass->input['plugin']);
	}
	
	function process_input_answer($question_id)
	{
		if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['q_type'] != 'single')
		{
			return -1;
		}
		
		$answered = array();
		foreach($this->ipsclass->input['answer'][$question_id] as $answer)
		{
			$answer = trim($this->ipsclass->parser->strip_all_tags($answer));
			if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['case_sensitive'])
			{
				$answer = strtolower($answer);
			}
			if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['space_sensitive'])
			{
				$answer = $this->remove_white_space($answer);
			}
			if(!$answer || in_array($answer,$answered))
			{
				continue;
			}
			$answered[] = $answer;
		}
		
		if(count($answered) == 0)
		{
			return 0;
		}
		elseif(count($answered) < $this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['match_choice'])
		{
			return -1;
		}
		
		$answers = array();
		foreach($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['answer'] as $answer)
		{
			$answer = trim($this->ipsclass->parser->strip_all_tags($answer));
			if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['case_sensitive'])
			{
				$answer = strtolower($answer);
			}
			if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['space_sensitive'])
			{
				$answer = $this->remove_white_space($answer);
			}
			if(!$answer || in_array($answer,$answers))
			{
				continue;
			}
			$answers[] = $answer;
		}
		
		$correct = 0;
		foreach($answered as $answer)
		{
			if(in_array($answer,$answers))
			{
				$correct++;
			}
		}
		
		return $correct == $this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['match_choice'] ? 1 : -1;
	}
	
	function process_single_multiple_choice($question_id)
	{
		if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['q_type'] != 'smultiple')
		{
			return -1;
		}
		
		if(!isset($this->ipsclass->input['answer'][$question_id]))
		{
			return 0;
		}
		
		return $this->ipsclass->input['answer'][$question_id] == $this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['answer'][0] ? 1 : -1;
	}
	
	function process_multiple_multiple_choice($question_id)
	{
		if($this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['q_type'] != 'mmultiple')
		{
			return -1;
		}
		
		if(count($this->ipsclass->input['answer'][$question_id]) == 0)
		{
			return 0;
		}
		elseif(count($this->ipsclass->input['answer'][$question_id]) < $this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['match_choice'])
		{
			return -1;
		}
		
		$correct = 0;
		foreach($this->ipsclass->input['answer'][$question_id] as $index => $check)
		{
			if(!$check)
			{
				continue;
			}
			
			$index = intval($index);
			
			if(in_array($index,$this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['answer']))
			{
				$correct++;
			}
		}
		
		return $correct == $this->ipsclass->cache['ibm_quiz_question'][$this->ipsclass->input['quiz']][$question_id]['match_choice'] ? 1 : -1;
	}
	
	function run_view_players()
	{
		$this->ipsclass->input['quiz'] = intval($this->ipsclass->input['quiz']);
		if(!is_array($this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]))
		{
			$this->ipsclass->Error(array('MSG'=>'quiz_no_quiz'));
		}
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['quiz_view_players'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}'>".$this->plugin['name']."</a>",$this->ipsclass->cache['ibm_quizzes'][$this->ipsclass->input['quiz']]['q_name'],$this->ipsclass->lang['quiz_view_players']);
		
		$members = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 't.*',
												'from' => array('market_quiz_taken'=>'t'),
												'where' => "t.quiz_id=".$this->ipsclass->input['quiz'],
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name, m.mgroup',
																				'from' => array('members'=>'m'),
																				'where' => "m.id=t.member_id",
																				'type' => 'left',
																			),
																	),
												'order' => "percent_correct DESC, time_start ASC",
										)	);
		$this->ipsclass->DB->exec_query();
		while($member = $this->ipsclass->DB->fetch_row())
		{
			$member['members_display_name'] = $this->ipsclass->market_class->format_name($member['member_id'], $member['members_display_name'],$member['mgroup']);
			$member['time_taken'] = $this->ipsclass->numbers->time_unit($member['time_taken']-$member['time_start'],'LONG');
			$member['time_start'] = $this->ipsclass->get_date($member['time_start'],'LONG');
			$member['percent_correct'] = $this->ipsclass->do_number_format($member['percent_correct']);
			$members[] = $member;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->quiz_list_quiz_takers($members);
	}
	
	function remove_white_space($text)
	{
		return str_replace(array(" ","\t","\n","\r","\0","\x0B"),"",$text);
	}
	
	function order($a,$b)
	{
		$time = time();
		if($a['q_ending_time'] >= $time && $b['q_ending_time'] >= $time)
		{
			if($a['q_ending_time'] > $b['q_ending_time'])
			{
				return 1;
			}
			elseif($a['q_ending_time'] < $b['q_ending_time'])
			{
				return -1;
			}
			else
			{
				return 0;
			}
		}
		elseif($a['q_ending_time'] >= $time)
		{
			return -1;
		}
		elseif($b['q_ending_time'] >= $time)
		{
			return 1;
		}
		else
		{
			if($a['q_ending_time'] > $b['q_ending_time'])
			{
				return -1;
			}
			elseif($a['q_ending_time'] < $b['q_ending_time'])
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
	}
}
?>